package org.softmed.rest.editor;

import java.awt.Color;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JTextField;
import javax.swing.border.Border;

import org.restlet.Client;
import org.restlet.data.Response;
import org.restlet.resource.StringRepresentation;
import org.softmed.rest.editor.commons.SwingUtil;
import org.softmed.rest.editor.comps.CustomTextField;

public class EditorUtil {
	public static final int buttonHeightAndWidth = 18;
	public static final int textFieldHeight = 20;
	// public static final int smallestHeight = 25;
	public static final Border buttonBorder = BorderFactory
			.createLineBorder(Color.GRAY);
	public static final int smallestHeight = 25;
	public static final int restBrowserWidth = 330;
	public static final int smallestInsets = 2;
	public static final int smallestWidth = 360;
	public static final int smallWidth = 400;
	public static final int width = 550;
	public static final Color red = new Color(255, 187, 187);
	public static final Color green = new Color(187, 255, 171);
	private static UpdateFrame updateFrame;

	public static void configButton(JButton button) {
		button.setBorder(EditorUtil.buttonBorder);
		SwingUtil.setSize(button, EditorUtil.buttonHeightAndWidth,
				EditorUtil.buttonHeightAndWidth);
	}

	public static void saveTextField(Client client, String instanceURI,
			CustomTextField field, String fieldName) {
		String content = field.getText();
		Response response = null;
		EditorUtil.showUpdatePanel();
		if (content == null || content.length() == 0) {
			response = client.delete(instanceURI + "/" + fieldName);
		} else {
			response = client.put(instanceURI + "/" + fieldName,
					new StringRepresentation(content));
		}

		EditorUtil.hideUpdatePanel();

		if (response.getStatus().getCode() != 200)
			throw new RuntimeException("Error changing app " + fieldName
					+ " to " + content);
		field.clean();
	}

	public static void showUpdatePanel() {
		if (updateFrame != null)
			return;

		updateFrame = new UpdateFrame();
		Thread thread = new Thread(new Runnable() {

			@Override
			public void run() {
				updateFrame.display();

			}

		});

		thread.start();
	}

	public static void hideUpdatePanel() {
		if (updateFrame != null) {
			updateFrame.setVisible(false);
			updateFrame.dispose();
			updateFrame = null;
		}

	}

}
